﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace TrabalhoWeb
{
    public partial class UserControlCadCategoria : System.Web.UI.UserControl
    {
        DAL.Categoria cat = new DAL.Categoria();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PreencheGrid();
            }
        }

        private void PreencheGrid()
        {
            grvCategorias.DataSource = cat.Categorias();
            grvCategorias.DataBind();
        }

        protected void grvCategorias_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            switch(e.CommandName)
            {
                case "excluir":
                    try
                    {
                        cat.DeletaCategoria(Convert.ToInt32(e.CommandArgument));
                        PreencheGrid();
                    }
                    catch(Exception ex)
                    {
                        ExibirAlerta("Erro ao deletar:\n"+ex.Message);
                    }
                    break;
                case "editar":
                    DataTable dt = new DataTable();
                    dt = cat.ListarCategorias(Convert.ToInt32(e.CommandArgument));
                    lblId.Text = dt.Rows[0]["ID"].ToString();
                    txtNome.Text = dt.Rows[0]["NOME"].ToString();
                    txaDescricao.Text = dt.Rows[0]["DESCRICAO"].ToString();
                    break;
            }
        }

        protected void btnSalvar_Click(object sender, EventArgs e)
        {
            try
            {
                cat.InsereAlteraCategoria(lblId.Text == "0" ? null : (int?)int.Parse(lblId.Text),
                    txtNome.Text,
                    txaDescricao.Text
                    );
                PreencheGrid();
            }catch(Exception ex)
            {
                ExibirAlerta("Erro ao salvar:\n"+ex.Message);
            }
        }

        protected void btnVoltar_Click(object sender, EventArgs e)
        {

        }


        public void ExibirAlerta(string strTexto)
        {
            System.Web.UI.ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "MSG", "alert('" + strTexto + "')", true);
        }

    }
}